package uc

import (
	log "github.com/sirupsen/logrus"
	"net"
	"thomas-mesh/discovery"
)

var SendChan = make(chan Packet, 1024)
var ReceiveChan = make(chan Packet, 1024)
var PushConn net.Conn

func init() {
	discovery.FetchAndCache("uc-connector")
	log.Printf("fetch uc-connector address:%s", discovery.CacheAdrress["uc-connector"])
}

func Connect(addr string) {
	defer func() {
		if e := recover(); e != nil {
			log.Errorf("recover:%v", e)
		}
	}()
	netAddr, _ := net.ResolveTCPAddr("tcp4", addr)
	tcpListener, error := net.ListenTCP("tcp4", netAddr)
	if error == nil {
		log.Infof("tcp listen: %s", addr)
	} else {
		log.Error(error)
		return
	}

	// 处理发送逻辑
	client := Client{}
	go func() {
		defer func() {
			if e := recover(); e != nil {
				log.Printf("recover:%v", e)
			}
		}()
		handleSendAndReceive(client)
	}()

	for {
		con, error := tcpListener.Accept()
		if error == nil {
			go HandleServerTcpCon(con, SendChan)
			PushConn = con
		} else {
			con.Close()
		}
	}
}

func handleSendAndReceive(client Client) {
	for {
		select {
		// 发送逻辑
		case p := <-SendChan:
			log.Infof("reqType:%v, packetId:%v, packType:%v , length:%v", p.ReqType, p.PacketId, p.PacketType, p.BodyLength)
			// 服务发现
			address := discovery.DiscoveryService("uc-connector")
			if address != "" && &address != nil {
				client.Write(address, p.Bytes())
			}
		// 接收逻辑
		case p := <-ReceiveChan:
			log.Infof("reqType:%v, packetId:%v, packType:%v , length:%v", p.ReqType, p.PacketId, p.PacketType, p.BodyLength)
			conn := SendMap[p.PacketId]
			// 避免空指针
			if conn != nil {
				conn.Write(p.Bytes())
				SendMap[p.PacketId] = nil
			} else {
				if PushConn != nil {
					log.Info("消息推送:packetId:", p.PacketId)
					PushConn.Write(p.Bytes())
				} else {
					log.Error("PushConn is nil")
				}
			}
		}
	}
}
